package cn.zhfeat.hatch.web.service.impl.system;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.zhfeat.core.base.BaseResultModel;
import cn.zhfeat.core.base.ResultStatus;
import cn.zhfeat.core.shiro.ShiroSessionData;
import cn.zhfeat.hatch.dto.company.CompanyDepartmentDto;
import cn.zhfeat.hatch.dto.sysuser.SysUserDto;
import cn.zhfeat.hatch.entity.company.CompanyDepartment;
import cn.zhfeat.hatch.entity.sysuser.SysUser;
import cn.zhfeat.hatch.rpc.IAccountRpcService;
import cn.zhfeat.hatch.rpc.IDepartmentRpcService;
import cn.zhfeat.hatch.web.bean.ExportDepartment;
import cn.zhfeat.hatch.web.service.IDepartmentService;
import cn.zhfeat.hatch.web.utils.ConfigUtil;
import cn.zhfeat.hatch.web.utils.ShiroSessionDataUtil;
import cn.zhfeat.utils.DateUtils;
import cn.zhfeat.utils.ExportExcel;
import cn.zhfeat.utils.cache.CacheUtility;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageInfo;

/**
 * @description: 部门信息相关实现层
 * 
 *
 * @author ZhangHao
 * @date 2018年5月24日 下午1:30:23 
 * @version 1.0.0.1
 */
@Service("departmentService")
public class DepartmentServiceImpl implements IDepartmentService {

	@Autowired
	private IDepartmentRpcService departmentRpcService;

	@Autowired
	private IAccountRpcService accountRpcService;

	@Autowired
	private CacheUtility cacheUtility;

	private String categoryKey = "Department-Model"; // 缓存类别
	private String cacheKey = "Department-Import-Mark"; // 缓存功能

	/**
	 * @return
	 * @description: 查询公司下全部的部门信息，用于展示部门树
	 * @author ZhangHao
	 * @date 2018年5月24日 下午1:33:50
	 * @version 1.0.0.1
	 */
	@Override
	public Object ajaxSelectAllDepartment(CompanyDepartmentDto dto) {

		BaseResultModel baseResultModel = new BaseResultModel();

		//获取用户所绑定的参数
		ShiroSessionData shiroSessionData = ShiroSessionDataUtil.getShiroSessionData();
		dto.setCid(shiroSessionData.getCid());
		dto.setShiroSessionData(shiroSessionData);

		//调用Rrpc接口返回所有部门
		List<CompanyDepartment> list = departmentRpcService.findListByDto(dto);

		//遍历所有部门，查询部门下的全部部门数量、当前该部门的员工数量
		for (int i = 0; i < list.size(); i++) {
			CompanyDepartmentDto companyDepartmentDto = new CompanyDepartmentDto();
			companyDepartmentDto.setParentDeptId(list.get(i).getId());
			List<CompanyDepartment> childrens = departmentRpcService.findListbyParentDeptId(companyDepartmentDto);
			SysUserDto sysUserDto = new SysUserDto();
			sysUserDto.setDepartmentId(list.get(i).getId());
			sysUserDto.setCid(shiroSessionData.getCid());
			List<SysUser> userLists = accountRpcService.findListByDto(sysUserDto);
			String departCode = list.get(i).getCode();
			if (departCode == null) {
				departCode = "";
			}
			list.get(i).setTitle(childrens.size() + "个部门,负责人:" + list.get(i).getLeaderName() + ",部门编码:" + departCode + "," + userLists.size());
		}

		if (list != null && list.size() > 0) {
			baseResultModel.setData(list);
			baseResultModel.setStatus(ResultStatus.SUCCESS.getStatusCode());
			baseResultModel.setMessage(ResultStatus.SUCCESS.getStatusMessage());
		} else {
			baseResultModel.setStatus(ResultStatus.HTTP_REQUEST_ERROR.getStatusCode());
			baseResultModel.setMessage(ResultStatus.HTTP_REQUEST_ERROR.getStatusMessage());
		}
		return baseResultModel;
	}

	/**
	 * @param dto
	 * @return
	 * @description: 分页查询部门信息
	 * @author ZhangHao
	 * @date 2018年5月26日 上午10:03:05
	 * @version 1.0.0.1
	 */
	@Override
	public BaseResultModel ajaxPageInfoByDto(CompanyDepartmentDto dto) {
		//获取用户所绑定的参数
		ShiroSessionData shiroSessionData = ShiroSessionDataUtil.getShiroSessionData();
		dto.setCid(shiroSessionData.getCid());
		dto.setShiroSessionData(shiroSessionData);
		BaseResultModel baseResultModel = new BaseResultModel();
		PageInfo<CompanyDepartment> page = departmentRpcService.ajaxPageInfoByDto(dto);
		List<CompanyDepartment> departments = page.getList();
		if (departments != null && departments.size() > 0) {
			//获取部门的人数
			for (CompanyDepartment companyDepartment : departments) {
				SysUserDto userDto = new SysUserDto();
				userDto.setCid(dto.getCid());
				userDto.setDepartmentId(companyDepartment.getId());
				List<SysUser> userList = accountRpcService.findListByDto(userDto);
				companyDepartment.setCount(userList.size());
			}
			baseResultModel.setData(departments);
			baseResultModel.setStatus(ResultStatus.SUCCESS.getStatusCode());
			baseResultModel.setMessage(ResultStatus.SUCCESS.getStatusMessage());
			baseResultModel.setTotalCount(new Long(page.getTotal()).intValue());
		} else {
			baseResultModel.setStatus(ResultStatus.NO_RECORD.getStatusCode());
			baseResultModel.setMessage(ResultStatus.NO_RECORD.getStatusMessage());
		}
		return baseResultModel;
	}

	/**
	 * @param entity
	 * @return
	 * @description: 新增部门信息
	 * @author ZhangHao
	 * @date 2018年5月26日 下午2:35:47
	 * @version 1.0.0.1
	 */
	@Override
	public BaseResultModel ajaxCreateDepartment(CompanyDepartment entity) {

		BaseResultModel baseResultModel = new BaseResultModel();

		//获取用户所绑定的参数
		ShiroSessionData shiroSessionData = ShiroSessionDataUtil.getShiroSessionData();
		entity.setCid(shiroSessionData.getCid());
		CompanyDepartmentDto dto = new CompanyDepartmentDto();
		dto.setParentDeptId(entity.getParentDeptId());
		dto.setCid(shiroSessionData.getCid());
		List<CompanyDepartment> list = departmentRpcService.findListbyParentDeptId(dto);


		//查询全部的部门
		CompanyDepartmentDto companyDepartmentDto = new CompanyDepartmentDto();
		companyDepartmentDto.setCid(shiroSessionData.getCid());
		List<CompanyDepartment> departments = departmentRpcService.findListByDto(companyDepartmentDto);

		//拿到当前要添加的部门层级的id
		Long id = entity.getParentDeptId();

		//用于保存当前层级上一共有多少层级的集合
		List<CompanyDepartment> cjList = new ArrayList<CompanyDepartment>();

		//查询部门层级
		while (true) {
			Boolean tag = true;
			for (int i = 0; i < departments.size(); i++) {
				//拿到父层级
				if (id.equals(departments.get(i).getId())) {
					tag = false;
					cjList.add(departments.get(i));
					id = departments.get(i).getParentDeptId();
					break;
				}
			}
			if (tag) {
				break;
			}
		}

		if (cjList != null && cjList.size() == 100) {
			baseResultModel.setStatus(ResultStatus.NO_RECORD.getStatusCode());
			baseResultModel.setMessage("部门层级请勿超过100个");
			return baseResultModel;
		}

		if (list.size() == 100) {
			baseResultModel.setStatus(ResultStatus.NO_RECORD.getStatusCode());
			baseResultModel.setMessage("同一级部门请勿超过100个");
			return baseResultModel;
		}
		Boolean nameTag = true;
		for (int i = 0; i < list.size(); i++) {
			if (entity.getName().equals(list.get(i).getName())) {
				nameTag = false; //说明部门名称已存在
			}
		}
		CompanyDepartment companyDepartment = null;
		//如果部门名称不存在
		if (nameTag) {
			//判断部门编码是否重复
			companyDepartmentDto.setCode(entity.getCode());
			CompanyDepartment cdt = departmentRpcService.getCompanyDepartment(companyDepartmentDto);
			if (cdt != null) {
				baseResultModel.setStatus(ResultStatus.NO_RECORD.getStatusCode());
				baseResultModel.setMessage("部门编码请勿重复");
				return baseResultModel;
			}

			companyDepartment = departmentRpcService.insertSelective(entity);

		} else {
			baseResultModel.setStatus(ResultStatus.NO_RECORD.getStatusCode());
			baseResultModel.setMessage("同级部门下部门名称请勿重复");
			return baseResultModel;
		}

		if (companyDepartment != null) {
			baseResultModel.setStatus(ResultStatus.SUCCESS.getStatusCode());
			baseResultModel.setMessage(ResultStatus.SUCCESS.getStatusMessage());
		} else {
			baseResultModel.setStatus(ResultStatus.NO_RECORD.getStatusCode());
			baseResultModel.setMessage(ResultStatus.NO_RECORD.getStatusMessage());
		}
		return baseResultModel;
	}

	/**
	 * @param entity
	 * @return
	 * @description: 编辑部门信息
	 * @author ZhangHao
	 * @date 2018年5月26日 下午4:00:06
	 * @version 1.0.0.1
	 */
	@Override
	public BaseResultModel ajaxEditDepartment(CompanyDepartment entity) {
		BaseResultModel baseResultModel = new BaseResultModel();
		//获取用户所绑定的参数
		ShiroSessionData shiroSessionData = ShiroSessionDataUtil.getShiroSessionData();
		entity.setCid(shiroSessionData.getCid());
		entity.setUpdateTime(new Date());
		CompanyDepartmentDto dtoOne = new CompanyDepartmentDto();
		dtoOne.setId(entity.getId());
		dtoOne.setCid(shiroSessionData.getCid());
		CompanyDepartment entityOne = departmentRpcService.getCompanyDepartment(dtoOne);
		CompanyDepartmentDto dto = new CompanyDepartmentDto();
		dto.setParentDeptId(entityOne.getParentDeptId());
		dto.setCid(shiroSessionData.getCid());
		List<CompanyDepartment> list = departmentRpcService.findListbyParentDeptId(dto);
		Boolean nameTag = true;
		for (int i = 0; i < list.size(); i++) {
			//System.out.println(entity.getName() + "-----" + list.get(i).getName() + "----"+list.get(i).getId() + "----" + entity.getId());
			if (entity.getName().equals(list.get(i).getName()) && !list.get(i).getId().equals(entity.getId())) {
				nameTag = false; //说明部门名称已存在
			}
		}
		Integer s = 0;
		//如果部门名称不存在
		if (nameTag) {
			//查询全部的部门
			CompanyDepartmentDto companyDepartmentDto = new CompanyDepartmentDto();
			companyDepartmentDto.setCid(shiroSessionData.getCid());
			companyDepartmentDto.setCode(entity.getCode());
			CompanyDepartment cdt = departmentRpcService.getCompanyDepartment(companyDepartmentDto);
			if (cdt == null) {
				s = departmentRpcService.updateSelective(entity);
			} else if (cdt != null && cdt.getId().equals(entity.getId())) {
				s = departmentRpcService.updateSelective(entity);
			} else {
				baseResultModel.setStatus(ResultStatus.NO_RECORD.getStatusCode());
				baseResultModel.setMessage("部门编码请勿重复");
				return baseResultModel;
			}
		} else {
			baseResultModel.setStatus(ResultStatus.NO_RECORD.getStatusCode());
			baseResultModel.setMessage("该部门名称在同级已存在");
			return baseResultModel;
		}
		baseResultModel.setStatus(ResultStatus.SUCCESS.getStatusCode());
		baseResultModel.setMessage(ResultStatus.SUCCESS.getStatusMessage());
		return baseResultModel;
	}

	/**
	 * @param entity
	 * @return
	 * @description: 删除部门信息
	 * @author ZhangHao
	 * @date 2018年5月29日 上午10:22:24
	 * @version 1.0.0.1
	 */
	@Override
	public BaseResultModel alaxDeleteDepartment(CompanyDepartment entity) {
		BaseResultModel baseResultModel = new BaseResultModel();
		//获取用户所绑定的参数
		ShiroSessionData shiroSessionData = ShiroSessionDataUtil.getShiroSessionData();

		//查询该部门下是否有子部门，如果有，返回删除失败提示
		CompanyDepartmentDto dto = new CompanyDepartmentDto();
		dto.setParentDeptId(entity.getId());
		dto.setCid(entity.getCid());
		List<CompanyDepartment> lists = departmentRpcService.findListbyParentDeptId(dto);
		if (lists.size() > 0) {
			baseResultModel.setStatus(ResultStatus.HTTP_REQUEST_ERROR.getStatusCode());
			baseResultModel.setMessage("该部门下有子部门，不可删除");
			return baseResultModel;
		}
		//查询该部门下是否有子员工，如果有，返回删除失败提示
		SysUserDto sysUserDto = new SysUserDto();
		sysUserDto.setDepartmentId(entity.getId());
		sysUserDto.setCid(shiroSessionData.getCid());
		List<SysUser> sysUsers = accountRpcService.findListByDto(sysUserDto);
		if (sysUsers != null && sysUsers.size() > 0) {

			baseResultModel.setStatus(ResultStatus.HTTP_REQUEST_ERROR.getStatusCode());
			baseResultModel.setMessage("该部门下有员工或已停用的员工，不可删除");
			return baseResultModel;
		}

		entity.setIsDeleted(1);
		entity.setUpdateTime(new Date());
		Integer tag = departmentRpcService.updateSelective(entity);

		//重置用户负责的一组部门(TODO)
		//1、查询用户对应的一组部门数据权限


		//2、遍历按逗号分隔的一组部门权限


		//3、更新数据库中的用户对应的数据权限


		//4、更新缓存中的用户负责部门数据

		if (tag == 1) {
			baseResultModel.setStatus(ResultStatus.SUCCESS.getStatusCode());
			baseResultModel.setMessage(ResultStatus.SUCCESS.getStatusMessage());
		} else {
			baseResultModel.setStatus(ResultStatus.NO_RECORD.getStatusCode());
			baseResultModel.setMessage(ResultStatus.NO_RECORD.getStatusMessage());
		}
		return baseResultModel;
	}


	/**
	 * @param dto
	 * @return
	 * @description: 导出企业下的部门
	 * @author ZhangHao
	 * @date 2018年6月21日 下午2:31:53
	 * @version 1.0.0.1
	 */
	@Override
	public BaseResultModel exportDepartmentList(HttpServletResponse response, CompanyDepartmentDto dto) {
		BaseResultModel baseResultModel = new BaseResultModel();
		//获取用户所绑定的参数
		ShiroSessionData shiroSessionData = ShiroSessionDataUtil.getShiroSessionData();

		ExportExcel<ExportDepartment> excelTool = new ExportExcel<ExportDepartment>();
		List<ExportDepartment> dataList = new ArrayList<ExportDepartment>();

		String[] headers = {"上级部门", "部门名称", "部门类型", "部门负责人", "部门编号"};
		String fileName = "导出部门" + DateUtils.DateToString(new Date(), "yyyy-MM-dd");

		//查询全部的部门数据
		CompanyDepartmentDto companyDepartmentDto = new CompanyDepartmentDto();
		companyDepartmentDto.setCid(shiroSessionData.getCid());
		List<CompanyDepartment> departments = departmentRpcService.findListByDto(companyDepartmentDto);
		//遍历全部的部门数据
		for (int i = 0; i < departments.size(); i++) {
			ExportDepartment bean = new ExportDepartment();

			/** 该段用于获取用户的一组上级部门*/
			String departMentType = "";
			//递归查询所有上级部门
			List<CompanyDepartment> parentDepartments = new ArrayList<CompanyDepartment>();

			dgCategoryList(parentDepartments, departments, String.valueOf(departments.get(i).getId()));

			for (int o = 0; o < parentDepartments.size(); o++) {
				String dname = "";
				if (!parentDepartments.get(o).getName().equals(departments.get(i).getName())) {
					dname = parentDepartments.get(o).getName();
					//父部门只有一个，所以这里直接get(0)就好了
					departMentType = dname + "一" + departMentType;
				}
			}
			if (departMentType.length() > 0) {
				departMentType = departMentType.substring(0, departMentType.length() - 1);
			}

			bean.setSuperDepartmentsName(departMentType);
			bean.setDepartmentName(departments.get(i).getName());
			bean.setCompanyTypeName(departments.get(i).getCompanyType() == 1 ? "机构" : "团队");
			bean.setLeaderName(departments.get(i).getLeaderName());
			bean.setCode(departments.get(i).getCode());
			dataList.add(bean);
		}

		int state = excelTool.exportExcel(headers, dataList, fileName, response);
		if (state == 1) {
			baseResultModel.setStatus(ResultStatus.SUCCESS.getStatusCode());
			baseResultModel.setMessage(ResultStatus.SUCCESS.getStatusMessage());
		} else {
			baseResultModel.setStatus(ResultStatus.NO_RECORD.getStatusCode());
			baseResultModel.setMessage(ResultStatus.NO_RECORD.getStatusMessage());
		}
		return baseResultModel;
	}


	/**
	 * @description:  递归方法(部门递归,查询全部上级部门)
	 *
	 * @param
	 * @author ZhangHao
	 * @date 2018/10/29 10:52
	 * @version 1.0.0.1
	 * @return void
	 */

	@SuppressWarnings("unused")
	private void dgCategoryList(List<CompanyDepartment> parentList, List<CompanyDepartment> list, String myId) {
		//循环全部的部门
		for (CompanyDepartment c : list) {
			if (null != c && null != c.getId() && null != c.getParentDeptId()) {
				//拿到每个部门的id和父id
				String id = String.valueOf(c.getId());
				String pid = String.valueOf(c.getParentDeptId());
				//如果当前id与循环中的id相同
				if (myId.equals(id)) {
					//将每一轮查询出的父节点放入集合
					//c.setCompanyDepartmentList(parents);
					parentList.add(c);
					//将父节点的id传入递归方法
					dgCategoryList(parentList, list, pid);
				}
			}
		}
	}

	/**
	 * @param list
	 * @param myId
	 * @return
	 * @description: 根据部门id查询部门名称
	 * @author ZhangHao
	 * @date 2018年5月25日 下午8:09:40
	 * @version 1.0.0.1
	 */
	@SuppressWarnings("unused")
	private String getDepartmentNameById(List<CompanyDepartment> list, Long myId) {
		String name = "";
		for (int i = 0; i < list.size(); i++) {
			if (myId.equals(list.get(i).getId())) {
				name = list.get(i).getName();
				break;
			}
		}
		return name;
	}

	/**
	 * @param file
	 * @return
	 * @description: 导入部门层级
	 * @author ZhangHao
	 * @date 2018年6月22日 上午9:29:01
	 * @version 1.0.0.1
	 */
	@SuppressWarnings("resource")
	@Override
	public BaseResultModel importdataManage(MultipartFile file) {

		BaseResultModel baseResultModel = new BaseResultModel();
		//获取用户所绑定的参数
		ShiroSessionData shiroSessionData = ShiroSessionDataUtil.getShiroSessionData();
		Integer successCount = 0;
		//自定义的缓存标识
		final String redisCacheListKey = "sps-cid-" + shiroSessionData.getCid() + "-";

		List<CompanyDepartment> listError = new ArrayList<CompanyDepartment>();
		try {
			InputStream is = file.getInputStream();
			XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
			XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);

			if (xssfSheet.getLastRowNum() <= 500) {
				//判断导入的excel是否符合规则
				Boolean b = validationRules(xssfSheet);
				//如果导入的excel不符合规则
				if (!b) {
					baseResultModel.setStatus(ResultStatus.NO_RECORD.getStatusCode());
					baseResultModel.setMessage("请上传表格模板文件");
					return baseResultModel;
				}

				//从数据库中查询全部的部门
				CompanyDepartmentDto companyDepartmentDto = new CompanyDepartmentDto();
				companyDepartmentDto.setCid(shiroSessionData.getCid());
				List<CompanyDepartment> departments = departmentRpcService.findListByDto(companyDepartmentDto);
				//保存所有的部门及部门层级名称
				List<String> departLevelLists = new ArrayList<String>();

				List<Map<String, String>> departLevelListIdAndNames = new ArrayList<Map<String, String>>();

				//遍历所有的部门，拿到所有的根部门id，根据每个部门id，拿到一系列层级
				for (int i = 0; i < departments.size(); i++) {
					/** 该段用于获取用户的一组上级部门*/
					String departMentType = "";

					String departMentId = "";
					//递归查询所有上级部门
					List<CompanyDepartment> parentDepartments = new ArrayList<CompanyDepartment>();

					dgCategoryList(parentDepartments, departments, String.valueOf(departments.get(i).getId()));

					//如果没有父级部门，直接显示本部门
					if (parentDepartments == null || parentDepartments.size() == 0) {
						departMentType = getDepartmentNameById(departments, departments.get(i).getId());
						departMentId = departments.get(i).getId() + "";
					} else {
						for (int o = 0; o < parentDepartments.size(); o++) {
							//父部门只有一个，所以这里直接get(0)就好了
							departMentType = parentDepartments.get(o).getName() + "一" + departMentType;
							departMentId = parentDepartments.get(o).getId() + "一" + departMentId;
						}
						if (departMentType.length() > 0) {
							departMentType = departMentType.substring(0, departMentType.length() - 1);
							departMentId = departMentId.substring(0, departMentId.length() - 1);
						}
					}
					departLevelLists.add(departMentType);
					Map<String, String> map = new HashMap<String, String>();
					map.put(departMentType, departMentId);
					departLevelListIdAndNames.add(map);
				}


				// 在此处可判断导入的excel有多少条
				for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
					XSSFRow xssfRow = xssfSheet.getRow(rowNum);
					String importDepartmentLevels = getDepartmentLevel(xssfRow);
					List<String> importDepartmentInfos = getImportDepartmentInfo(xssfRow);

					List<String> oneGroupLists = new ArrayList<String>();
					String[] departmentArr = importDepartmentLevels.split("一");
					//先插入最大的一条
					oneGroupLists.add(importDepartmentLevels);
					//如果只有一个部门
					while (true) {
						//如果数组的长度大于1，那么截取字符串一最后出现的位置
						if (departmentArr.length > 1) {
							String dpl = importDepartmentLevels.substring(0, importDepartmentLevels.lastIndexOf("一"));
							oneGroupLists.add(dpl);
							importDepartmentLevels = dpl;
							String[] da = new String[departmentArr.length - 1];
							for (int a = 0; a < departmentArr.length - 1; a++) {
								da[a] = departmentArr[a];
							}
							departmentArr = da;
						} else {
							break;
						}

					}
					//倒叙排序
					Collections.reverse(oneGroupLists);


                    //用于记录上级部门的id
					Long parentId = 0l;
					//记录导入的当前部门层级名称,按"一"分割
					String remarkDepartLevelName = "";
					//记录导入的当前部门层级id,按"一"分割
					String remarkDepartLevelId = "";

					//遍历用户导入的每一行记录的每个部门，和全部部门层级进行匹配，如果没匹配上，增加该部门并获取id。如果匹配的上，记录该部门的id用于增加下一个部门
					for (int p = 0; p < oneGroupLists.size(); p++) {
						Boolean tag = false;
                        if(!oneGroupLists.get(p).contains("SCRM|ERRPR|部门名称格式错误|10011|REMARK")){
						//遍历所有的部门层级
						for (int o = 0; o < departLevelLists.size(); o++) {
                                if (departLevelLists.get(o).equals(oneGroupLists.get(p))) {
                                    tag = true;
                                    continue;
                                }
						}
                        }else{
                            tag = true;
                        }

                        //为异常记录提示导出使用
                        CompanyDepartment cdt = new CompanyDepartment();
                        cdt.setDepartmentNameLevels(oneGroupLists.get(p));
                        cdt.setCompanyTypeName(importDepartmentInfos.get(0));
                        cdt.setLeaderName(importDepartmentInfos.get(1));

                        //如果该部门存在，不导入，记录当前部门id，并给予用户提示
						if (tag) {
						    if(cdt.getDepartmentNameLevels().contains("SCRM|ERRPR|部门名称格式错误|10011|REMARK")){
                                cdt.setDepartmentNameLevels(cdt.getDepartmentNameLevels().replace("SCRM|ERRPR|部门名称格式错误|10011|REMARK","部门名称格式错误"));
                                listError.add(cdt);
                            }else{
                                //拿到已存在的部门id
                                String ids = getDepartLevelIds(oneGroupLists.get(p), departLevelListIdAndNames);
                                String[] dpId = ids.split("一");
                                parentId = Long.valueOf(dpId[dpId.length - 1]);
                            }
							//如果该部门不存在，导入，拿到返回的部门id
						} else {
							Integer depNumTj = 0;
							//根据父ID，判断同级部门数量是否大于等于10，如果大于或等于10.那么则不导入
							for (int d = 0; d < departments.size(); d++) {
								if (departments.get(d).getParentDeptId().equals(parentId)) {
									depNumTj += 1;
								}
							}
							if (depNumTj >= 10) {
								//给予用户提示
								listError.add(cdt);
							} else {
								CompanyDepartment entity = new CompanyDepartment();
								String[] dpName = oneGroupLists.get(p).split("一");
								String deName = dpName[dpName.length - 1];
								String code = generate();
								//部门名称
								entity.setName(deName);
								//部门类型
								String bmlx = importDepartmentInfos.get(0);
								//部门负责人
								String bmfzr = importDepartmentInfos.get(1);
								//如果部门类型为空
								if (bmlx == null && "".equals(bmlx)) {
									//给予用户提示 
									listError.add(cdt);
								} else {
									if ("机构".equals(bmlx)) {
										entity.setCompanyType(1);
									} else if ("团队".equals(bmlx)) {
										entity.setCompanyType(2);
									}
                                    if(entity.getCompanyType() != null){
                                        if (entity.getCompanyType() == 1 || entity.getCompanyType() == 2) {

                                            entity.setCode(code);
                                            entity.setParentDeptId(parentId);
                                            entity.setLeaderName(bmfzr);
                                            entity.setCid(shiroSessionData.getCid());
                                            entity = departmentRpcService.insertSelective(entity);
                                            parentId = entity.getId();
                                            successCount += 1; //成功入库，记录数加1
                                            remarkDepartLevelName += entity.getName() + "一";
                                            remarkDepartLevelId += parentId + "一";
                                            //把新加入的部门层级名称加入全部部门集合中
                                            departLevelLists.add(remarkDepartLevelName.substring(0, remarkDepartLevelName.length() - 1));
                                            //把新加入的id层级加入全部部门集合中
                                            Map<String, String> map = new HashMap<String, String>();
                                            map.put(remarkDepartLevelName.substring(0, remarkDepartLevelName.length() - 1), remarkDepartLevelId.substring(0, remarkDepartLevelId.length() - 1));
                                            departLevelListIdAndNames.add(map);
                                        } else {
                                            //给予用户提示
                                            listError.add(cdt);
                                        }
                                    }else{
                                        //给予用户提示
                                        listError.add(cdt);
                                    }
								}
							}
						}
					}
				}

				xssfWorkbook.close();
				is.close();

				//将导入失败的记录放入redis
				cacheUtility.getCacheDataManager().putStringValue(categoryKey, cacheKey, redisCacheListKey + ConfigUtil.IMPORT_MEMBER_ERROR_EXPORT, JSONArray.toJSONString(listError));

				baseResultModel.setStatus(ResultStatus.SUCCESS.getStatusCode());
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("successImport", successCount);
				map.put("errorImport", listError.size());
				baseResultModel.setData(map);
				// 将导出失败的数据根据Key放入redis,需申请一个key

			} else {
				// 导入的数据不能超过500条
				baseResultModel.setStatus("3");
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("successImport", 0);
				map.put("errorImport", 0);
			}

		} catch (Exception e) {
			baseResultModel.setStatus("0");
			e.printStackTrace();
		}
		return baseResultModel;
	}

	/**
	 * @return
	 * @description:验证规则
	 * @author ZhangHao
	 * @date 2018年6月22日 下午1:32:34
	 * @version 1.0.0.1
	 */
	public Boolean validationRules(XSSFSheet xssfSheet) {

		Boolean b = true;
		XSSFRow xssfRow = xssfSheet.getRow(0);

		//获得第一列
		XSSFCell cell0 = xssfRow.getCell(0);
		//获得第二列
		XSSFCell cell1 = xssfRow.getCell(1);
		//获得第三列
		XSSFCell cell2 = xssfRow.getCell(2);
		//获得第四列
		XSSFCell cell3 = xssfRow.getCell(3);
		//获得第五列
		XSSFCell cell4 = xssfRow.getCell(4);
		//获得第六列
		XSSFCell cell5 = xssfRow.getCell(5);
		//获得第七列
		XSSFCell cell6 = xssfRow.getCell(6);
		//获得第八列
		XSSFCell cell7 = xssfRow.getCell(7);
		//获得第九列
		XSSFCell cell8 = xssfRow.getCell(8);
		//获得第十列
		XSSFCell cell9 = xssfRow.getCell(9);
		//获得第十一列
		XSSFCell cell10 = xssfRow.getCell(10);
		//获得第十二列
		XSSFCell cell11 = xssfRow.getCell(11);

		//一级部门
		String row0 = "";
		if (cell0 != null) {
			row0 = cell0.getStringCellValue();
		}
		//二级部门
		String row1 = "";
		if (cell1 != null) {
			row1 = cell1.getStringCellValue();
		}
		//三级部门
		String row2 = "";
		if (cell2 != null) {
			row2 = cell2.getStringCellValue();
		}
		//四级部门
		String row3 = "";
		if (cell3 != null) {
			row3 = cell3.getStringCellValue();
		}
		//五级部门
		String row4 = "";
		if (cell4 != null) {
			row4 = cell4.getStringCellValue();
		}
		//六级部门
		String row5 = "";
		if (cell5 != null) {
			row5 = cell5.getStringCellValue();
		}
		//七级部门
		String row6 = "";
		if (cell6 != null) {
			row6 = cell6.getStringCellValue();
		}
		//八级部门
		String row7 = "";
		if (cell7 != null) {
			row7 = cell7.getStringCellValue();
		}
		//九级部门
		String row8 = "";
		if (cell8 != null) {
			row8 = cell8.getStringCellValue();
		}
		//十级部门
		String row9 = "";
		if (cell9 != null) {
			row9 = cell9.getStringCellValue();
		}

		//部门类型
		String row10 = "";
		if (cell10 != null) {
			row10 = cell10.getStringCellValue();
		}
		//部门负责人
		String row11 = "";
		if (cell11 != null) {
			row11 = cell11.getStringCellValue();
		}


		if (!"一级部门".equals(row0)) {
			b = false;
		} else if (!"二级部门".equals(row1)) {
			b = false;
		} else if (!"三级部门".equals(row2)) {
			b = false;
		} else if (!"四级部门".equals(row3)) {
			b = false;
		} else if (!"五级部门".equals(row4)) {
			b = false;
		} else if (!"六级部门".equals(row5)) {
			b = false;
		} else if (!"七级部门".equals(row6)) {
			b = false;
		} else if (!"八级部门".equals(row7)) {
			b = false;
		} else if (!"九级部门".equals(row8)) {
			b = false;
		} else if (!"十级部门".equals(row9)) {
			b = false;
		} else if (!"部门类型".equals(row10)) {
			b = false;
		} else if (!"部门负责人".equals(row11)) {
			b = false;
		}

		return b;
	}

	/**
	 * @return
	 * @description:获取用户导入的部门层级
	 * @author ZhangHao
	 * @date 2018年6月22日 下午3:48:23
	 * @version 1.0.0.1
	 */
	public String getDepartmentLevel(XSSFRow xssfRow) {

		//获得第一列
		XSSFCell cell0 = xssfRow.getCell(0);
		//获得第二列
		XSSFCell cell1 = xssfRow.getCell(1);
		//获得第三列
		XSSFCell cell2 = xssfRow.getCell(2);
		//获得第四列
		XSSFCell cell3 = xssfRow.getCell(3);
		//获得第五列
		XSSFCell cell4 = xssfRow.getCell(4);
		//获得第六列
		XSSFCell cell5 = xssfRow.getCell(5);
		//获得第七列
		XSSFCell cell6 = xssfRow.getCell(6);
		//获得第八列
		XSSFCell cell7 = xssfRow.getCell(7);
		//获得第九列
		XSSFCell cell8 = xssfRow.getCell(8);
		//获得第十列
		XSSFCell cell9 = xssfRow.getCell(9);

		//一级部门
		String row0 = "";
		if (cell0 != null) {
		    if(!"".equals(cell0.getStringCellValue())){
                row0 = cell0.getStringCellValue();
            }else{
                row0 = "SCRM|ERRPR|部门名称格式错误|10011|REMARK";
            }
		}
		//二级部门
		String row1 = "";
		if (cell1 != null) {
            if(!"".equals(cell1.getStringCellValue())) {
                row1 = cell1.getStringCellValue();
            }else{
                row1 = "SCRM|ERRPR|部门名称格式错误|10011|REMARK";
            }
		}
		//三级部门
		String row2 = "";
		if (cell2 != null) {
            if(!"".equals(cell2.getStringCellValue())) {
                row2 = cell2.getStringCellValue();
            }else{
                row2 = "SCRM|ERRPR|部门名称格式错误|10011|REMARK";
            }
		}
		//四级部门
		String row3 = "";
		if (cell3 != null) {
            if(!"".equals(cell3.getStringCellValue())) {
                row3 = cell3.getStringCellValue();
            }else{
                row3 = "SCRM|ERRPR|部门名称格式错误|10011|REMARK";
            }
		}
		//五级部门
		String row4 = "";
		if (cell4 != null) {
            if(!"".equals(cell4.getStringCellValue())) {
                row4 = cell4.getStringCellValue();
            }else{
                row4 = "SCRM|ERRPR|部门名称格式错误|10011|REMARK";
            }
		}
		//六级部门
		String row5 = "";
		if (cell5 != null) {
            if(!"".equals(cell5.getStringCellValue())) {
                row5 = cell5.getStringCellValue();
            }else{
                row5 = "SCRM|ERRPR|部门名称格式错误|10011|REMARK";
            }
		}
		//七级部门
		String row6 = "";
		if (cell6 != null) {
            if(!"".equals(cell6.getStringCellValue())) {
                row6 = cell6.getStringCellValue();
            }else{
                row6 = "SCRM|ERRPR|部门名称格式错误|10011|REMARK";
            }
		}
		//八级部门
		String row7 = "";
		if (cell7 != null) {
            if(!"".equals(cell7.getStringCellValue())) {
                row7 = cell7.getStringCellValue();
            }else{
                row7 = "SCRM|ERRPR|部门名称格式错误|10011|REMARK";
            }
		}
		//九级部门
		String row8 = "";
		if (cell8 != null) {
            if(!"".equals(cell8.getStringCellValue())) {
                row8 = cell8.getStringCellValue();
            }else{
                row8 = "SCRM|ERRPR|部门名称格式错误|10011|REMARK";
            }
		}
		//十级部门
		String row9 = "";
		if (cell9 != null) {
            if(!"".equals(cell9.getStringCellValue())) {
                row9 = cell9.getStringCellValue();
            }else{
                row9 = "SCRM|ERRPR|部门名称格式错误|10011|REMARK";
            }
		}

		String departmentLevels = "";
		//加入一级部门
		if (row0 != null && !"".equals(row0)) {
			departmentLevels += row0;
		}
		//加入二级部门
		if (row1 != null && !"".equals(row1)) {
			departmentLevels += "一" + row1;
		}
		//加入三级部门
		if (row2 != null && !"".equals(row2)) {
			departmentLevels += "一" + row2;
		}
		//加入四级部门
		if (row3 != null && !"".equals(row3)) {
			departmentLevels += "一" + row3;
		}
		//加入五级部门
		if (row4 != null && !"".equals(row4)) {
			departmentLevels += "一" + row4;
		}
		//加入六级部门
		if (row5 != null && !"".equals(row5)) {
			departmentLevels += "一" + row5;
		}
		//加入七级部门
		if (row6 != null && !"".equals(row6)) {
			departmentLevels += "一" + row6;
		}
		//加入八级部门
		if (row7 != null && !"".equals(row7)) {
			departmentLevels += "一" + row7;
		}
		//加入九级部门
		if (row8 != null && !"".equals(row8)) {
			departmentLevels += "一" + row8;
		}
		//加入十级部门
		if (row9 != null && !"".equals(row9)) {
			departmentLevels += "一" + row9;
		}

		return departmentLevels;
	}

	/**
	 * @param names
	 * @return
	 * @description: 根据一组部门层级，获取对应的id
	 * @author ZhangHao
	 * @date 2018年6月24日 下午10:15:16
	 * @version 1.0.0.1
	 */
	public String getDepartLevelIds(String names, List<Map<String, String>> list) {
		String LevelIds = "";
		for (int i = 0; i < list.size(); i++) {
			Map<String, String> map = list.get(i);
			if (map.get(names) != null) {
				LevelIds = map.get(names);
				break;
			}
		}
		return LevelIds;
	}

	/**
	 * @param xssfRow
	 * @return
	 * @description: 获取部门类型和部门负责人
	 * @author ZhangHao
	 * @date 2018年6月24日 下午11:19:39
	 * @version 1.0.0.1
	 */
	public List<String> getImportDepartmentInfo(XSSFRow xssfRow) {

		//获得第十一列
		XSSFCell cell10 = xssfRow.getCell(10);

		//获得第十二列
		XSSFCell cell11 = xssfRow.getCell(11);

		//九级部门
		String row10 = "";
		if (cell10 != null) {
			row10 = cell10.getStringCellValue();
		}
		//十级部门
		String row11 = "";
		if (cell11 != null) {
			row11 = cell11.getStringCellValue();
		}
		List<String> list = new ArrayList<String>();

		list.add(row10);
		list.add(row11);

		return list;

	}

	/**
	 * @return
	 * @description: 获取6位字母数字混合字符串
	 * @author ZhangHao
	 * @date 2018年6月25日 上午12:06:08
	 * @version 1.0.0.1
	 */
	public String generate() {

		String randomcode = "";
		// 用字符数组的方式随机
		String model = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		char[] m = model.toCharArray();
		for (int j = 0; j < 6; j++) {
			char c = m[(int) (Math.random() * 36)];
			// 保证六位随机数之间没有重复的
			if (randomcode.contains(String.valueOf(c))) {
				j--;
				continue;
			}
			randomcode = randomcode + c;
		}
		return randomcode;
	}

	/**
	 * @param request
	 * @param response
	 * @description: 导出导入部门失败的列表
	 * @author ZhangHao
	 * @date 2018年6月26日 上午10:33:00
	 * @version 1.0.0.1
	 */
	@Override
	public void exportListError(HttpServletRequest request, HttpServletResponse response) {
		ShiroSessionData sessionData = ShiroSessionDataUtil.getShiroSessionData();

		BufferedWriter writer = null;
		try {
			String[] headers = {"上级部门", "部门名称", "部门类型", "部门负责人"};
			Calendar now = Calendar.getInstance();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			String fileName = "导出失败列表" + sdf.format(now.getTime()) + ".csv";
			response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
			OutputStream os = response.getOutputStream();
			writer = new BufferedWriter(new OutputStreamWriter(os, "gbk"));
			for (int i = 0; i < headers.length; i++) {
				String s = headers[i];
				writer.write(s);
				if (i < headers.length - 1) {
					writer.write(",");
				} else {
					writer.newLine();
				}
			}
			writer.flush();
		} catch (Exception e) {
			e.printStackTrace();
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}

		String redisCacheListKey = "sps-cid-" + sessionData.getCid() + "-";
		String errorList = cacheUtility.getCacheDataManager().getStringValue(categoryKey, cacheKey,
				redisCacheListKey + ConfigUtil.IMPORT_MEMBER_ERROR_EXPORT);
		if (errorList != null) {
			List<CompanyDepartment> ListMap = JSONArray.parseArray(errorList, CompanyDepartment.class);
			for (int i = 0; i < ListMap.size(); i++) {
				CompanyDepartment department = ListMap.get(i);
				String departmentNameLevels = department.getDepartmentNameLevels() != null ? department.getDepartmentNameLevels() : "";
				String[] dnl = departmentNameLevels.split("一");
				String companyTypeName = department.getCompanyTypeName() != null ? department.getCompanyTypeName() : "";
				String leaderName = department.getLeaderName() != null ? department.getLeaderName() : "";
				String name = dnl[dnl.length - 1];
				String realDepartmentNameLevels = "";
				if (dnl.length > 1) {
					realDepartmentNameLevels = departmentNameLevels.substring(0, departmentNameLevels.lastIndexOf("一"));
				} else {
					realDepartmentNameLevels = departmentNameLevels;
				}
				try {
					writer.write(realDepartmentNameLevels + "," + name + "," + companyTypeName + "," + leaderName);
					writer.newLine();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			try {
				writer.flush();
				writer.close();
			} catch (Exception e) {
				e.printStackTrace();
				if (writer != null) {
					try {
						writer.close();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			}
		}
	}

	/**
	 * 功能描述 根据cid和部门id获取组织架构名称
	 *
	 * @param departMentId
	 * @return
	 * @author Duansy
	 * @date
	 */
	public String getOutDepartMentNameByIdUtil(List<CompanyDepartment> list, long departMentId) {
		List<CompanyDepartment> parentDepartments = new ArrayList<CompanyDepartment>();

		dgCategoryList(parentDepartments, list, String.valueOf(departMentId));
		String departMentType = "";

		//如果没有父级部门，直接显示本部门
		if (parentDepartments == null || parentDepartments.size() == 0) {
			return getDepartmentNameById(list, departMentId);
		} else {
			for (int o = 0; o < parentDepartments.size(); o++) {
				//父部门只有一个，所以这里直接get(0)就好了
				String dname = "";
//				if(!parentDepartments.get(o).getName().equals(list.get(i).getName())) {
				dname = parentDepartments.get(o).getName();
				//父部门只有一个，所以这里直接get(0)就好了
				departMentType = dname + "、" + departMentType;
//				}
			}
			return departMentType;
		}
	}

	/**
	 *功能描述 获取公司所有组织架构
	 * @author Duansy
	 * @date
	 * @param cid
	 * @return
	 */
	public List<CompanyDepartment>  getOutCompanyDepartListUtil(long cid){
		CompanyDepartmentDto companyDepartmentDto = new CompanyDepartmentDto();
		companyDepartmentDto.setCid(cid);
		return departmentRpcService.findListByDto(companyDepartmentDto);
	}
}